﻿using System;
using System.Reflection;
using System.Text;

namespace KC.Service.Core.Attribute
{
    public static class GetCacheKeyUtil
    {
        public static Func<MethodBase, object[], string, int, string> CacheKeyGenerator = CacheKeyGenerator = (method, inputs, tenantName, groupInputIndex) =>
        {
            var sb = new StringBuilder();
            if (groupInputIndex >= 0 && inputs.Length > groupInputIndex)
                sb.AppendFormat("group-" + inputs[groupInputIndex].ToString().ToLower() + "-");
            sb.AppendFormat("{0}-", !string.IsNullOrWhiteSpace(tenantName) ? tenantName.ToLower() : "com");
            sb.AppendFormat("{0}-", method.DeclaringType != null ? method.DeclaringType.FullName : "namespace");
            sb.AppendFormat("{0}-", method.Name);
            if (inputs != null)
            {
                Array.ForEach(inputs, input =>
                {
                    if (input is string || input is int || input is float || input is decimal)
                    {
                        sb.AppendFormat("{0}-", input.ToString());
                    }
                    else
                    {
                        string hashCode = (input == null) ? "" : input.GetHashCode().ToString();
                        sb.AppendFormat("{0}-", hashCode);
                    }
                });
            }
            return sb.ToString().TrimEnd('-');
        };
        public static Func<string, object[], string, int, string> CustomerCacheKeyGenerator = (keyPrex, inputs, tenantName, groupInputIndex) =>
        {
            var sb = new StringBuilder();
            if (groupInputIndex >= 0)
                sb.AppendFormat("group-" + inputs[groupInputIndex].ToString().ToLower() + "-");
            sb.AppendFormat("{0}-", !string.IsNullOrWhiteSpace(tenantName) ? tenantName.ToLower() : "com");
            sb.AppendFormat("{0}-", keyPrex);
            if (inputs != null)
            {
                Array.ForEach(inputs, input =>
                {
                    if (input is string || input is int || input is float || input is decimal)
                    {
                        sb.AppendFormat("{0}-", input.ToString());
                    }
                    else
                    {
                        string hashCode = (input == null) ? "" : input.GetHashCode().ToString();
                        sb.AppendFormat("{0}-", hashCode);
                    }
                });
            }
            return sb.ToString().TrimEnd('-');
        };
    }
}
